﻿Ext.BLANK_IMAGE_URL = '/script/ext/resources/images/s.gif';
Ext.onReady(function () {
    //初始化快速提示
    Ext.QuickTips.init();
    var modelid = jQuery.query.get("modelid");
    //将提示显示在form属性旁边
    Ext.form.Field.prototype.msgTarget = "side";
    //创建根节点
    var DepmetTreeRoot = new Ext.tree.AsyncTreeNode({ text: '文件柜树', id: 'DepmetTreeRoot', expanded: true, leaf: false });
    //创建树面板
    var DepmetTree = new Ext.tree.TreePanel({
        loader: new Ext.tree.TreeLoader({ dataUrl: "server/Contacts/ContactsTypeList.aspx" }),
        id: 'DepmetTree',
        region: 'west',
        width: 160,
        margins: '5 5 0 5',
        cmargins: '5',
        bodyStyle: "padding:5px;",
        title: "人物关系",
        rootVisible: false,
        lines: true,
        autoScroll: true,
        animate: true,
        collapsible: true,
        containerScroll: true,
        tbar: [{
            iconCls: 'icon-add', text: "新建", tooltip: '新建', handler: function () {
                Ext.Msg.prompt("新建角色", "新角色名称：", function (btn, text) {
                    if (btn == "ok") {
                        Ext.Ajax.request({
                            url: 'server/Contacts/ContactsTypeAdd.aspx?modelid=' + modelid,
                            success: function (data) {
                                var json = Ext.util.JSON.decode(data.responseText);
                                if (json.success) {
                                    Ext.Msg.alert("完成", json.msg);
                                    DepmetTree.loader.load(DepmetTreeRoot);
                                } else {
                                    Ext.Msg.alert("失败", json.msg);
                                }
                            },
                            failure: function () {
                                Ext.Msg.alert("消息", "请求失败");
                            },
                            params: { CommunityClasstext: text }
                        });
                    }
                });
            }
        }, {
            iconCls: 'icon-edit', text: "编辑", tooltip: '编辑', handler: function () {
                var model = DepmetTree.getSelectionModel();
                var selectNode = model.getSelectedNode();
                if (selectNode) {
                    Ext.Msg.prompt("编辑角色", "新角色名称：", function (btn, text) {
                        if (btn == "ok") {
                            if (text != selectNode.text) {
                                Ext.Ajax.request({
                                    url: 'server/Contacts/ContactsTypeAdd.aspx?modelid=' + modelid,
                                    success: function (data) {
                                        var json = Ext.util.JSON.decode(data.responseText);
                                        if (json.success) {
                                            Ext.Msg.alert("完成", json.msg);
                                            DepmetTree.loader.load(DepmetTreeRoot);
                                        } else {
                                            Ext.Msg.alert("失败", json.msg);
                                        }
                                    },
                                    failure: function () {
                                        Ext.Msg.alert("消息", "请求失败");
                                    },
                                    params: { CommunityClasstext: text, CommunityClassid: selectNode.id }
                                });
                            } else {
                                Ext.Msg.alert("消息", "没用更新");
                            }
                        }
                    }, "", "", selectNode.text);
                }
            }
        }, {
            iconCls: 'icon-del', text: "删除", tooltip: '删除', handler: function () {
                Ext.Msg.confirm("警告", "确认要删除此角色数据？", function (btn) {
                    if (btn == "yes") {
                        var model = DepmetTree.getSelectionModel();
                        var selectNode = model.getSelectedNode();
                        if (selectNode) {
                            Ext.Ajax.request({
                                url: 'server/Contacts/ContactsTypeDel.aspx?modelid=' + modelid,
                                success: function (data) {
                                    var json = Ext.util.JSON.decode(data.responseText);
                                    if (json.success) {
                                        Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                        DepmetTree.loader.load(DepmetTreeRoot);
                                    } else {
                                        Ext.Msg.alert("失败", json.msg);
                                    }
                                },
                                failure: function () {
                                    Ext.Msg.alert("消息", "请求失败");
                                },
                                params: { CommunityClassid: selectNode.id }
                            });
                        }
                    }
                });
            }
        }]
    });
    DepmetTree.setRootNode(DepmetTreeRoot);
    DepmetTree.on('dblclick', function (node, e) {
        e.stopEvent();
        var model = DepmetTree.getSelectionModel();
        var selectNode = model.getSelectedNode();
        if (selectNode) {
            groupStore.load({ params: { start: 0, limit: pageSize, ClassId: selectNode.id} });
        }
    });
    DepmetTree.on('checkchange', function (node, checked) {
        selectParentNode(node, checked);
        selectChildNode(node, checked);
    }, DepmetTree);

    //定义数据模型
    var UserInfo = new Ext.data.Record.create([
                        { name: 'ID', type: 'int', mappging: "ID" },
                        { name: 'ContactsName', type: 'string', mappging: "ContactsName" },
                        { name: 'ContactsSex', type: 'bool', mappging: "ContactsSex" },
                        { name: 'ContactsCall', type: 'string', mappging: "ContactsCall" },
                        { name: 'ContactsQQ', type: 'string', mappging: "ContactsQQ" },
                        { name: 'ContactsMS", type: 'string', mappging: "ContactsMSN" },
                        { name: 'ContactsEmail', type: 'string', mappging: "ContactsEmail" },
                        { name: 'ContactsPhone', type: 'string', mappging: "ContactsPhone" },
                        { name: 'ContactsCellPhone', type: 'string', mappging: "ContactsCellPhone" },
                        { name: 'ContactsFax', type: 'string', mappging: "ContactsFax" },
                        { name: 'ContactsAddress', type: 'string', mappging: "ContactsAddress" },
                        { name: 'ContactsCode', type: 'string', mappging: "ContactsCode" },
                        { name: 'ContactsURL', type: 'string', mappging: "ContactsURL" },
                        { name: 'ContactsBirthday', mappging: "ContactsBirthday" },
                        { name: 'ContactsRemark', type: 'string', mappging: "ContactsRemark" },
                        { name: 'ContactsType', type: 'string', mappging: "ContactsType" }
                        ]);

    /*创建数据源*/
    var groupStore = new Ext.data.GroupingStore({
        proxy: new Ext.data.HttpProxy({ url: "server/Contacts/ContactsList.aspx" }),
        reader: new Ext.data.JsonReader({ totalProperty: "Count", root: "List" }, UserInfo),
        sortInfo: { field: 'ID', direction: 'DESC' }
    });
    //设置每页条数
    var pageSize = 20;
    var cookiePageSize = parseInt(Ext.util.Cookies.get("pageSize"));
    if (cookiePageSize) { pageSize = cookiePageSize; }
    //加载数据源
    groupStore.load({ params: { start: 0, limit: pageSize} });
    //创建选择列模型
    var sm = new Ext.grid.CheckboxSelectionModel();
    //定义列模型
    var cm = new Ext.grid.ColumnModel([
            sm,
            { id: 'ID', header: '编号', dataIndex: 'ID', width: 60, sortable: true },
            { id: 'ContactsName', header: '姓名', dataIndex: 'ContactsName', width: 120, sortable: true },
            { id: 'ContactsSex', header: '性别', dataIndex: 'ContactsSex', width: 80, sortable: true, renderer: function (v) { if (v) { return "男"; } else { return "女"; } } },
            { id: 'ContactsBirthday', header: '生日', dataIndex: 'ContactsBirthday', width: 150, sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d'), format: "Y-m-d" },
            { id: 'ContactsQQ', header: 'QQ', dataIndex: 'ContactsQQ', width: 80, sortable: true },
            { id: 'ContactsEmail', header: '邮箱', dataIndex: 'ContactsEmail', width: 80, sortable: true },
            { id: 'ContactsPhone', header: '固定电话', dataIndex: 'ContactsPhone', width: 120, sortable: true },
            { id: 'ContactsCellPhone', header: '手机', dataIndex: 'ContactsCellPhone', width: 120, sortable: true }
            ]);

    //创建下[每页行数]拉框
    var comboBox = new Ext.form.ComboBox({
        width: 50,
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        title: "每页行数",
        emptyText: pageSize,
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: ['myId', 'displayText'],
            data: [[10, 10], [20, 20], [30, 30], [50, 50], [100, 100]]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    comboBox.on("select", function (combo, record, index) {
        Ext.util.Cookies.set("pageSize", record.id);
        window.location.reload();
    });

    //定义备注
    var remark = new Ext.form.TextArea({
        fieldLabel: '备注', //标签名称 
        anchor: '100%',
        height: 140,
        name: "ContactsRemark"
    });



    //            //查看按钮
    //            var uform = new Ext.form.FormPanel({
    //                width: 300,
    //                border: false,
    //                frame: true,
    //                labelAlign: "right",
    //                buttonAlign: "right",
    //                labelWidth: 60,
    //                defaultType: "textfield",
    //                border: false,
    //                items: [
    //                    { name: "ID", fieldLabel: "编号", width: 180, dataIndex: 'ID', sortable: true },
    //                    { name: "ContactsName", fieldLabel: "姓名", width: 180 },
    //                    { name: "ContactsCall", fieldLabel: "称呼", width: 180 },
    //                    { name: "ContactsBirthday", fieldLabel: "生日", width: 180, xtype: 'datefield', format: "Y-m-d", value: new Date() },
    //                    { name: "ContactsQQ", fieldLabel: "QQ", width: 180 },
    //                    { name: "ContactsMSN", fieldLabel: "MSN", width: 180 },
    //                    { name: "ContactsEmail", fieldLabel: "邮箱", width: 180 },
    //                    { name: "ContactsPhone", fieldLabel: "固定电话", width: 180 },
    //                    { name: "ContactsCellPhone", fieldLabel: "手机", width: 180 },
    //                    { name: "ContactsFax", fieldLabel: "传真", width: 180 },
    //                    { name: "ContactsAddress", fieldLabel: "地址", width: 180 },
    //                    { name: "ContactsCode", fieldLabel: "邮编", width: 180 },
    //                    { name: "ContactsURL", fieldLabel: "个人网址", width: 180 }
    //                ]
    //            });

    //            //查看信息窗口
    //            var win = new Ext.Window({
    //                border: false,
    //                title: "详细信息",
    //                items: uform,
    //                iconCls: 'icon-search-16',
    //                buttonAlign: "center",
    //                buttons: [{
    //                    iconCls: 'icon-search-16',
    //                    text: "关闭",
    //                    handler: function () {

    //                    }
    //                }],
    //                closeAction: "hide"
    //            });


    //信息检索内容
    var form = new Ext.form.FormPanel({
        border: false,
        frame: true,
        labelAlign: "right",
        buttonAlign: "right",
        labelWidth: 100,
        items: [new Ext.form.TextField({
            allowBlank: false,
            fieldLabel: '请输入姓名查询',
            labelStyle: 'color:red',
            name: 'Name', //
            blankText: '姓名不能为空',
            anchor: '100%'
        })]
    });
    //信息检索窗口
    var win2 = new Ext.Window({
        border: false,
        width: 400,
        title: "信息检索",
        width: 640,
        items: form,
        iconCls: 'icon-search-16',
        buttonAlign: "center",
        buttons: [{
            iconCls: 'icon-search-16',
            text: "开始检索",
            handler: function () {
                if (form.form.isValid()) {
                    var key = form.getForm().findField("Name").getValue();
                    groupStore.load({ params: { key: key, start: 0, limit: pageSize} });
                }
            }
        }, {
            text: "重置表单",
            handler: function () { form.getForm().reset(); }
        }],
        closeAction: "hide"
    });

    var grid = new Ext.grid.GridPanel({
        title: "用户列表",
        store: groupStore,
        border: true,
        margins: '5 5 0 0',
        region: 'center',
        view: new Ext.grid.GroupingView(),
        sm: sm,
        cm: cm,
        tbar: [{
            iconCls: 'icon-add',
            text: '添加',
            value: 0,
            handler: function (btn) {
                UserForm.setTitle("信息添加");
                UserForm.getForm().reset();
                viewport.items.get(2).expand();
            }
        }, {
            ref: '../removeBtn',
            iconCls: 'icon-del',
            text: '删除',
            disabled: true,
            handler: function () {
                Ext.MessageBox.confirm("确认提示", "确认要删除所选行数据？", function (btn) {
                    if (btn == "yes") {
                        var s = grid.getSelectionModel().getSelections();
                        var delR = new Array();
                        var delRid = new Array();
                        for (var i = s.length - 1; i >= 0; i--) {
                            var r = s[i];
                            if (r.get('ID') != undefined) { delRid.push(r.get('ID')); delR.push(r); }
                        }
                        Ext.Ajax.request({
                            url: "server/Contacts/ContactsDel.aspx?modelid=" + modelid,
                            method: 'POST',
                            params: { id: delRid },
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    for (var i = 0; i < delR.length; i++) {
                                        if (json.ids.valueOf(delR[i].get('ID'))) { groupStore.remove(delR[i]) }
                                    }
                                    Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                } else {
                                    Ext.Msg.alert("错误", json.msg);
                                }
                            }
                        });
                    }
                });
            }
        }, {
            ref: '../viewBtn',
            iconCls: 'icon-view',
            text: '查看',
            disabled: true,
            handler: function (btn) {
                var s = grid.getSelectionModel().getSelections();
                window.open('server/Contacts/ContactsDetailList.aspx?id2=' + s[0].get("ID"));

                //网页显示在窗口中
                //                var list = grid.getSelectionModel().getSelections();
                //                var win = new Ext.Window({
                //                    border: false,
                //                    title: "详细信息",
                //                    autoLoad: { url: "server/Contacts/ContactsDetailList.aspx", scripts: true, params: { 'id2': list[0].get("ID")} },
                //                    iconCls: 'icon-search-16',
                //                    buttonAlign: "center",
                //                    buttons: [{
                //                        iconCls: 'icon-search-16',
                //                        text: "关闭",
                //                        handler: function () {

                //                        }
                //                    }],
                //                    closeAction: "hide"
                //                });

                //                win.show();

                //详细信息显示在窗口中
                //                        var list = grid.getSelectionModel().getSelections();
                //                        var itemid = list[0].get("ID");
                //                        uform.getForm().load({
                //                            url: "server/Contacts/ContactsSelectList.aspx",
                //                            params: { itemid: itemid },
                //                            method: "POST",
                //                            success: function (form, action) {
                //                                form.setValues(action.result);
                //                            },
                //                            failure: function (form, action) {
                //                                form.setValues(action.result);
                //                            }
                //                        });
                //                        win.show();
            }
        }, {
            iconCls: 'icon-search-16',
            text: '信息查询',
            handler: function (btn) {
                win2.show();
            }
        }],
        bbar: new Ext.PagingToolbar({
            store: groupStore,
            pageSize: pageSize,
            displayInfo: true,
            prependButtons: true,
            items: ['每页行数', comboBox, '-'],
            displayMsg: "本页显示第{0}条到第{1}条数据，共{2}条",
            emptyMsg: "暂无记录"
        })
    });

    //定义通讯录类别
    //    var ContactsTypeTree = new Ext.form.ComboBoxTree({
    //        name: "myDepmet",
    //        width: 143,
    //        fieldLabel: "请选择",
    //        hiddenName: "ContactsTypeID",
    //        listEmptyText: "*暂无信息*",
    //        emptyText: "请选择",
    //        editable: false,
    //        resizable: true,
    //        tree: new Ext.tree.TreePanel({
    //            root: new Ext.tree.AsyncTreeNode({ text: '文件夹', id: '0', leaf: false }),
    //            lines: true,
    //            rootVisible: false,
    //            border: false,
    //            dataUrl: "server/Contacts/ContactsTypeList.aspx"
    //        })
    //    });



    var ContactsTypeTree = new Ext.ux.ComboBoxTree({
        fieldLabel: "人物关系",
        hiddenName: "ContactsTypeID",
        name: "myDepmet",
        width: 143,
        emptyText: "人物关系",
        allowBlank: false,  //不允许为空
        editable: false,
        selectNodeModel: 'all',
        tree: {
            xtype: 'treepanel',
            lines: true, rootVisible: false, border: false,
            loader: new Ext.tree.TreeLoader({ dataUrl: 'server/Contacts/ContactsTypeList.aspx' }),
            root: new Ext.tree.AsyncTreeNode({ text: '选文件夹', id: "0", leaf: false })
        }
    });





    //定义性别
    var radiogroup = new Ext.form.RadioGroup({
        width: 120,
        fieldLabel: "性别",
        items: [{
            boxLabel: '男',
            inputValue: "true",
            name: "radiog",
            checked: true
        }, {
            boxLabel: '女',
            name: "radiog",
            inputValue: "false"
        }]
    });

    var UserForm = new Ext.form.FormPanel({
        region: 'south',
        title: "编辑信息",
        margins: "0 5 5 0",
        collapsible: true,
        expanded: false,
        frame: true,
        split: false,
        height: 300,
        labelAlign: "right",
        labelWidth: 70,
        buttonAlign: "center",
        items: [{
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ID",
                    fieldLabel: "编号",
                    disabled: true,
                    width: 140
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsName",
                    fieldLabel: "姓名",
                    allowBlank: false,  //不允许为空
                    blankText: '姓名不能为空',  //不允许为空给的提示
                    regex: /[\u4e00-\u9fa5]/,  //正则表达式在/...../之间.
                    regexText: "只能输入中文!", //正则表达式错误提示
                    width: 140
                }]
            }, {
                columnWidth: .3,
                layout: 'form',
                items: [{
                    columnWidth: .5,
                    layout: "form",
                    items: [radiogroup]
                }]

            }, {
                columnWidth: .2,
                layout: 'form',
                items: ContactsTypeTree
            }]
        }, {//行2
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsCall",
                    fieldLabel: "称呼",
                    width: 140
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    name: "ContactsBirthday",
                    fieldLabel: "生日",
                    xtype: 'datefield',
                    format: "Y-m-d",
                    width: 143
                }]
            }, {
                columnWidth: .3,
                layout: 'form',
                items: [{
                    columnWidth: .5,
                    layout: "form",
                    items: [{
                        xtype: 'textfield',
                        name: "ContactsQQ",
                        fieldLabel: "QQ",
                        width: 140
                    }]
                }]

            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsMSN",
                    fieldLabel: "MSN",
                    width: 140
                }]
            }]
        }, {//行3
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsEmail",
                    fieldLabel: "邮箱",
                    width: 140
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsPhone",
                    fieldLabel: "固定电话",
                    width: 140
                }]
            }, {
                columnWidth: .3,
                layout: 'form',
                items: [{
                    columnWidth: .5,
                    layout: "form",
                    items: [{
                        xtype: 'textfield',
                        name: "ContactsCellPhone",
                        fieldLabel: "手机",
                        width: 140
                    }]
                }]

            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsFax",
                    fieldLabel: "传真",
                    width: 140
                }]
            }]
        }, {//行4
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsAddress",
                    fieldLabel: "地址",
                    width: 140
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsCode",
                    fieldLabel: "邮编",
                    width: 140
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ContactsURL",
                    fieldLabel: "个人网址",
                    width: 140
                }]
            }]
        }, new Ext.form.HtmlEditor({
            fieldLabel: '备注', //标签名称 
            anchor: '100%',
            height: 140,
            name: "ContentText"
        })],
        buttons: [{
            id: "saveBtn",
            text: "确定",
            handler: function () {

                if (UserForm.form.isValid()) {

                    var params = {
                        ID: UserForm.getForm().findField("ID").getValue(),
                        ContactsSex: UserForm.getForm().getValues()["radiog"],
                        ContactsType: ContactsTypeTree.getCtValue()
                    };
                    UserForm.getForm().submit({
                        method: "POST",
                        params: params,
                        url: "server/Contacts/ContactsAdd.aspx?modelid=" + modelid,
                        success: function (form, action) {
                            if (action.result.success) {
                                Ext.Msg.alert("请求成功", action.result.msg, function () {
                                    groupStore.load({ params: { start: 0, limit: pageSize} });
                                });
                                UserForm.getForm().reset();
                            } else {
                                Ext.Msg.alert("错误", action.result.msg);
                            }
                        },
                        failure: function (form, action) { Ext.Msg.alert("请求失败", action); }
                    });
                }
            }
        }, {
            text: "重置",
            handler: function () { UserForm.getForm().reset(); }
        }]
    });
    //创建页面布局
    var viewport = new Ext.Viewport({ layout: 'border', items: [DepmetTree, grid, UserForm] });
    viewport.items.get(2).collapse();
    //布局加载
    viewport.doLayout();
    //延时加载
    setTimeout(function () { Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({ remove: true }); }, 400);
    //有选择行启用删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.viewBtn.setDisabled(sm.getCount() < 1 || sm.getCount() > 1);
    });
    grid.on('rowdblclick', function (g, index, e) {
        viewport.items.get(2).expand();
        var r = g.getSelectionModel().getSelected();
        if (r != null) {
            UserForm.form.loadRecord(new UserInfo({ 'ID': r.get("ID"), 'radiog': (r.get("ContactsSex") ? r.get("ContactsSex") : "false"), 'ContactsCall': r.get("ContactsCall"), 'ContactsName': r.get("ContactsName"), 'ContactsQQ': r.get("ContactsQQ"), 'ContactsMS": r.get("ContactsMSN"), 'ContactsEmail': r.get("ContactsEmail"), 'ContactsPhone': r.get("ContactsPhone"), 'ContactsCellPhone': r.get("ContactsCellPhone"), 'ContactsFax': r.get("ContactsFax"), 'ContactsAddress': r.get("ContactsAddress"), 'ContactsCode': r.get("ContactsCode"), 'ContactsURL': r.get("ContactsURL"), 'ContactsBirthday': r.get("ContactsBirthday"), 'ContactsRemark': r.get("ContactsRemark"), 'ContactsTypeID': GetContacTypetName(r.get("ContactsType")) }));

//            ContactsTypeTree.setCtValue(GetFoldersName(r.get("ParentID")), r.get("ParentID"));

            //        Ext.get('parent_id').dom.value = r.get("ContactsTypeID");
            UserForm.doLayout();
        }
    });
});